﻿/// <reference path="jquery-1.7-vsdoc.js" />

/*
Yihaodian XO Group Helper

relation resource
http://code.jquery.com/jquery-1.4.1-vsdoc.js
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7-vsdoc.js
*://www.yihaodian.com/tuangou/index.do?grouponId=*
*/

// ==UserScript==
// @name 		Yihaodian XO Group Helper
// @namespace		http://www.dummy.com/
// @description Auto check yihaodian XO Group state, Auto buy when starting
// @include		*://www.yihaodian.com/tuangou/*

// ==/UserScript==

function withjQuery(callback, safe)
{
    if (typeof (jQuery) == "undefined")
    {
        var script = document.createElement("script");
        script.type = "text/javascript";
        // http://code.jquery.com/jquery-1.7.1.min.js
        // https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
        script.src = "http://code.jquery.com/jquery-1.7.1.min.js";

        if (safe)
        {
            var cb = document.createElement("script");
            cb.type = "text/javascript";
            cb.textContent = "jQuery.noConflict();(" + callback.toString() + ")(jQuery);";
            script.addEventListener('load', function ()
            {
                document.head.appendChild(cb);
            });
        }
        else
        {
            var dollar = undefined;
            if (typeof ($) != "undefined") dollar = $;
            script.addEventListener('load', function ()
            {
                jQuery.noConflict();
                $ = dollar;
                callback(jQuery);
            });
        }
        document.head.appendChild(script);
    }
    else
    {
        callback(jQuery);
    }
}

withjQuery(function ()
{
    var XOConfig =
    {
        CHECK_INTERVAL: 10000,
        BASE_CHECK_URL: "http://www.yihaodian.com/tuangou/grouponBuyVerify.do?grouponId={0}&timestamp=1",
        BASE_VIEW_URL: "http://www.yihaodian.com/tuangou/index.do?grouponId={0}",
        BASE_BUY_URL: "http://www.yihaodian.com/tuangou/grouponBuy.do?grouponId={0}",
        PRODUCT_NAME: "XO Check",
        AUTO_BUY_AMOUNT : 5
    };

    var XOHelper =
    {
        QueryString: function (name)
        {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null)
            {
                return unescape(r[2]);
            }
            else
            {
                return null;
            }
        },
        StringFormat: function (string)
        {
            var args = arguments;
            var pattern = new RegExp("{([0-" + arguments.length + "])}", "g");
            return String(string).replace(pattern, function (match, index)
            {
                var currentIndex = parseInt(index);
                if (currentIndex + 1 > args.length || currentIndex < 0)
                {
                    throw new Error("参数索引出错");
                }
                return args[currentIndex + 1];
            });
        },
        InjectStyle: function ()
        {
            // create stylesheet
            var styleInject;
            styleInject = document.createElement("style");
            styleInject.id = 'injectStyle'
            styleInject.type = "text/css";
            styleInject.textContent = "#todaybox { position:relative; } \r\n" +
            "#InjectContainer { z-index:999999;position:absolute; top: 0px; left:0px; border:1px solid blue; background-color:white; } \r\n" +
            ".DefaultInjectContainer {width:100px;height:40px;} \r\n" +
            ".BigInjectContainer { width:160px;height:60px; padding:3px; }  \r\n" +
            "#ButtonController{ width:100px; display: block} \r\n" +
            "#divXONoticeMsg{ z-index:999999;position:absolute;width:250px; right:150px; top:150px; background-color:#ADCBF7; text-align:center; font-size:20px; display:none; color:red; padding: 10px; }"

            document.head.appendChild(styleInject);
        }
    };

    var __XOCheckHelper =
    {
        // controls
        DivInjectContainer: null,
        ButtonController: null,
        SpanSummary: null,

        // field
        IntervalHandle: null,
        CheckCount: 0,
        LastCheckTime: new Date(),

        Init: function ()
        {
            // create controls
            this.DivInjectContainer = jQuery("<div id='InjectContainer'></div>");
            this.ButtonController = jQuery("<input id='ButtonController' type='button' value='XO Start' />");
            this.ButtonController.click(this.ButtonClick);
            this.SpanSummary = jQuery("<span id='SpanSummary'></span>");

            this.DivInjectContainer.append(this.ButtonController);
            this.DivInjectContainer.append(this.SpanSummary);

            // #todaybox is out container
            jQuery('#todaybox').append(this.DivInjectContainer);
        },
        UpdateSummary: function (ext)
        {
            var str = "";
            str += "CheckCount = " + __XOCheckHelper.CheckCount + "<br/>";
            str += "LastCheckTime = " + __XOCheckHelper.LastCheckTime.getHours().toString() + ":" + __XOCheckHelper.LastCheckTime.getMinutes().toString() + ":" + __XOCheckHelper.LastCheckTime.getSeconds().toString() + "<br/>";
            str += ext + "<br/>";
            this.SpanSummary.html(str);
        },
        ButtonClick: function ()
        {
            if (__XOCheckHelper.IntervalID == null)
            {
                __XOCheckHelper.Start();
            }
            else
            {
                __XOCheckHelper.Stop();
            }
        },
        Start: function ()
        {
            __XOCheckHelper.IntervalID = setInterval(__XOCheckHelper.CheckGroupState, XOConfig.CHECK_INTERVAL);
            __XOCheckHelper.ButtonController.val("XO Stop");
            __XOCheckHelper.DivInjectContainer.addClass("BigInjectContainer");
        },
        Stop: function ()
        {
            clearInterval(__XOCheckHelper.IntervalID);
            __XOCheckHelper.IntervalID = null;
            __XOCheckHelper.ButtonController.val("XO Start");
        },
        CheckGroupState: function ()
        {
            __XOCheckHelper.CheckCount++;
            __XOCheckHelper.LastCheckTime = new Date();
            __XOCheckHelper.UpdateSummary("Checking");

            jQuery.ajax(
            {
                url: XOHelper.StringFormat(XOConfig.BASE_CHECK_URL, XOHelper.QueryString("grouponId")), 
                type:"GET",
                cache:false,
                success : function(result)
                {
                    if (result == "ok")
                    {
                        __XOCheckHelper.OnSuccess();
                        // window.location = "";
                    }
                    else if (result.indexOf("已经过期") != -1)
                    {
                        __XOCheckHelper.Stop();
                        __XOCheckHelper.UpdateSummary("已经过期");
                    }
                    else if (result.indexOf("人数已满") != -1)
                    {
                        __XOCheckHelper.Stop();
                        __XOCheckHelper.UpdateSummary("人数已满");
                    }
                    else if (result.indexOf("还未开始") != -1)
                    {
                        __XOCheckHelper.UpdateSummary("还未开始");
                    }
                    else
                    {
                        // unknown
                    }
                },
                error : function()
                {
                    __XOCheckHelper.UpdateSummary("Check Error");
                }
            });
        },
        OnSuccess: function ()
        {
            window.location = XOHelper.StringFormat(XOConfig.BASE_BUY_URL, XOHelper.QueryString("grouponId"));
        }
    };

    var __XOBuyHelper =
    {
        Init: function ()
        {
            var msg = jQuery("<div id='divXONoticeMsg'>#msg</div>");

            var amount = parseFloat(jQuery("#totalAmount2").html());

            if (amount <= XOConfig.AUTO_BUY_AMOUNT)
            {
                doSaveByAccount();

                var remainToPay = parseFloat(jQuery("#remainToPay").html());
                if (remainToPay <= 0)
                {
                    jQuery(".input_ok_92").click();
                    return;
                }
                else
                {
                    __XOBuyHelper.ShowNotice("帐号余额不足,差￥" + remainToPay.toString());
                }
            }
            else
            {
                __XOBuyHelper.ShowNotice("当前团购不是XO");
            }
        },
        ShowNotice: function (content)
        {
            if (jQuery("#divXONoticeMsg").length == 0)
            {
                var ctrl = jQuery("<div id='divXONoticeMsg'>#msg</div>");
                ctrl.click(function ()
                {
                    ctrl.slideUp(1000);
                });
                jQuery("body").append(ctrl);
            }

            jQuery("#divXONoticeMsg").html(content).slideDown(500);
        }
    };

    XOHelper.InjectStyle();
    if (window.location.toString().indexOf("index.do?grouponId") != -1)
    {
        __XOCheckHelper.Init();
    }
    else if (window.location.toString().indexOf("grouponBuy.do") != -1)
    {
        __XOBuyHelper.Init();
    }
}, true);

